package com.wowoai.removewatermark.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.wowoai.common.basemodule.BusinessException;
import com.wowoai.common.enums.ResponseEnum;
import com.wowoai.common.factoy.OssClientFactory;
import com.wowoai.common.userInfo.CurrentUserInfo;
import com.wowoai.removewatermark.enums.RemoveWatermarkTypeEnum;
import com.wowoai.removewatermark.service.RemoveWatermarkServiceI;
import com.wowoai.user.enums.UserScoreOptionTypeEnum;
import com.wowoai.user.service.UserServiceI;
import com.wowoai.user.service.dto.UserDTO;
import com.wowoai.utils.FileDownloadUtils;
import com.wowoai.utils.HttpClientUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.util.*;

@Service
public class RemoveWatermarkServiceImpl implements RemoveWatermarkServiceI {

    private final OssClientFactory ossClientFactory;

    private final UserServiceI userServiceI;

    private static final String REMOVE_WATERMARK_PATH = "remove_watermark";

    @Value("${qsy.url:https://eeapi.cn/api/video/3271AA53FBE5B0579F94D24A6885116C999EB14DA67BBF31E1/2894/}")
    private String qsyUrl;


    public RemoveWatermarkServiceImpl(OssClientFactory ossClientFactory,UserServiceI userServiceI){
        this.userServiceI = userServiceI;
        this.ossClientFactory = ossClientFactory;
    }

    @SneakyThrows
    @Override
    @Transactional
    public Map<String, Object> detect(String url) {
        //先判断是否有积分去水印
        UserDTO userDTO = userServiceI.getUserByPhoneNumber(CurrentUserInfo.getUserInfo().getPhoneNumber());
        if ((userDTO.getScore() + userDTO.getPermanentScore()) < 1){
            throw new BusinessException(ResponseEnum.SUBTRACT_SCORE_FAIL.getCode(),"积分不足");
        }
        Set<String> urls = new HashSet<>();
        Map<String, Object> resultMap = new HashMap<>();
        Map<String,Object> queryParams = new HashMap<>();
        queryParams.put("url",url);
        String response = HttpClientUtil.doGet(qsyUrl, queryParams);
        JSONObject jsonObject = JSON.parseObject(response);
        Integer code = jsonObject.getInteger("code");
        Integer status = jsonObject.getInteger("status");
        JSONObject data = jsonObject.getJSONObject("data");
        String title = data.getString("title");
        if (Objects.isNull(code) || code != 200){
            throw new BusinessException(ResponseEnum.SUBTRACT_SCORE_FAIL.getCode(),title);
        }
        if (Objects.isNull(status) || status != 101){
            throw new BusinessException(ResponseEnum.SUBTRACT_SCORE_FAIL.getCode(),title);
        }
        String type = jsonObject.getString("type");
        String video = data.getString("video");
        JSONArray images = data.getJSONArray("images");
        if (StringUtils.hasText(video)){
            String fileUrl = video + "." + type;
            String ossUrl = uploadOss(fileUrl, type);
            if (StringUtils.hasText(ossUrl)){
                urls.add(ossUrl);
            }
            resultMap.put("type", RemoveWatermarkTypeEnum.VIDEO_TYPE.getCode());
            resultMap.put("urls",urls);
        }else if (Objects.nonNull(images)){
            type = "jpg";
            for (Object image : images) {
                String fileUrl = image.toString().split("\\.").length > 1 ? image.toString() : image + "." + type;
                String ossUrl = uploadOss(fileUrl, type);
                if (StringUtils.hasText(ossUrl)){
                    urls.add(ossUrl);
                }
            }
            resultMap.put("type",RemoveWatermarkTypeEnum.IMAGE_TYPE.getCode());
            resultMap.put("urls",urls);
        }
        //去除成功 扣积分
        userServiceI.updateScore(userDTO,1, UserScoreOptionTypeEnum.REMOVE_WATERMARK,"-1");
        return resultMap;
    }

    private String uploadOss(String fileUrl,String type) throws IOException {
        File file = FileDownloadUtils.downloadFile(fileUrl, type);
        if (Objects.nonNull(file)){
            InputStream inputStream = Files.newInputStream(file.toPath());
            MockMultipartFile multipartFile = new MockMultipartFile("file",file.getName(), "APPLICATION_OCTET_STREAM",inputStream);
            Date expiration = new Date(System.currentTimeMillis() + 60 * 100000);
            String ossUrl = ossClientFactory.upload(multipartFile, REMOVE_WATERMARK_PATH,expiration);
            file.delete();
            return ossUrl;
        }
        return null;
    }
}
